﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DnsClient;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Recommend.API.Models;
using Resilience;

namespace Recommend.API.Application.Services
{
    public class UserService
        : IUserService
    {
        //private readonly string _url = "http://localhost:8000";
        private readonly string _url;
        private readonly IDnsQuery _dnsQuery;
        //private readonly HttpClient _httpClient;
        private readonly IHttpClient _httpClient;
        private readonly IOptions<ServiceDiscoveryOptions> _serviceOptions;
        public UserService(IHttpClient httpClient,
            IDnsQuery dnsQuery,
            IOptions<ServiceDiscoveryOptions> serviceOptions)
        {
            _httpClient = httpClient;
            _dnsQuery = dnsQuery;
            _serviceOptions = serviceOptions;

            var services = _dnsQuery.ResolveService("service.consul", _serviceOptions.Value.UserServiceName);
            var addressList = services.First().AddressList;
            var host = addressList.Any() ? addressList.First().ToString() : services.First().HostName;
            var port = services.First().Port;
            _url = $"http://{host}:{port}";
        }
        public async Task<UserIdentity> GetUserInfoAsync(int userId)
        {
            var response = await _httpClient.GetStringAsync($"{_url}/api/users/GetUserInfoAsync?id=" + userId);
            if (!string.IsNullOrEmpty(response))
            {
                return JsonConvert.DeserializeObject<UserIdentity>(response);
            }
            return null;
        }
    }
}
